package com.one.group.admin.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * {@code @Create:}  2025-09-28  14 : 55
 * {@code @Author:} Cherry
 * {@code @ToUser:} 凡是发生,皆有利于我。
 * ------------------------------------
 * {@code @note:}
 */
@Configuration
public class PageHelperAutoConfiguration implements InitializingBean {
    private final List<SqlSessionFactory> sqlSessionFactoryList;

    public PageHelperAutoConfiguration(List<SqlSessionFactory> sqlSessionFactoryList) {
        this.sqlSessionFactoryList = sqlSessionFactoryList;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        PageInterceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("pageSizeZero", "true");
        properties.setProperty("autoRuntimeDialect", "true");
        interceptor.setProperties(properties);
        Iterator var2 = this.sqlSessionFactoryList.iterator();

        while (var2.hasNext()) {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) var2.next();
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            if (!this.containsInterceptor(configuration, interceptor)) {
                configuration.addInterceptor(interceptor);
            }
        }

    }

    private boolean containsInterceptor(org.apache.ibatis.session.Configuration configuration, Interceptor interceptor) {
        try {
            return configuration.getInterceptors().stream().anyMatch((config) -> {
                return interceptor.getClass().isAssignableFrom(config.getClass());
            });
        } catch (Exception var4) {
            return false;
        }
    }
}
